<?php

class LoginController extends Controller_Base
{

    function IndexAction()
    {
        $request = $this->getRequest();
        SmartyAdapter::$templateName = "user/login";
        $tokenAuth = new TokenAuth('login');
        SmartyAdapter::assign('token', $tokenAuth->access_token);
        //清除登录信息
        UserAuth::delAuth();
        if ($request->isPost()) {
            $mobile = $request->getPost('mobile', '');
            if (!$mobile) {
                AjaxTool::returnJsonData(401,'请填写手机号码');
            }
            $is_sms = $request->getPost('is_sms',0);
            if($is_sms){
                $token = $request->getPost('token');
                $mobile = $request->getPost('mobile', '');
                if (!$tokenAuth->isToken($token)) {
                    AjaxTool::returnJsonData(401,'token错误');
                }
                $code = $request->getPost('code');

                $actionData = array(
                    'source_type' => '1',
                    'action_type' => '4',
                    'action_time' => time(),
                    'action_uid' => '0',
                    'action_uname' => '',
                    'mobile' => trim($mobile),
                    'action_group' => 0,
                    'action_des' => '',
                    'action_res' => '1',
                    'action_main' => 'user',
                    'action_event' => 'login',
                );

                $admin = Module_User_Administrator::getInstance()->getByMobile($mobile);
                if (!$admin) {
                    $actionData['action_des'] = '登录失败，账号不存在';
                    $actionData['action_res'] = 0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    unset($actionData);
                    AjaxTool::returnJsonData(403,'登录失败，账号不存在');
                }
                if ($admin['status']==2) {
                    $actionData['action_des'] = '登录失败，该账号已被禁用,不允许登录';
                    $actionData['action_res'] = 0;
                    @Module_Uaction_Hook::onActionData($actionData);
                    unset($actionData);
                    AjaxTool::returnJsonData(403,'登录失败，该账号已被禁用,不允许登录');
                }
                if(!$this->checkUserIp($admin)){
                    AjaxTool::returnJsonData(403,'访问ip不在允许白名单内');
                }
                $check = Lib_Code::verifyCode($mobile, $code);
                if (!$check) {
                    AjaxTool::returnJsonData(403,'请输入正确的短信验证码');
                }
                $actionData['action_uid'] = $admin['id'];
                $actionData['action_uname'] = $admin['name'];
                $actionData['action_group'] = $admin['role_id'];
                $actionData['action_des'] = '登录成功';
                $actionData['action_res'] = 1;
                @Module_Uaction_Hook::onActionData($actionData);
                //保存用户登录信息
                $random_key = UserAuth::setAuth($mobile);
                Module_User_Administrator::getInstance()->updateRandomKeyById($admin['id'], $random_key);
                $config = Yaf_Registry::get("config")->cookie;
                setcookie('random_key', $random_key, null, '/', $config['domain']);
                //登录成功清除token_access
                $tokenAuth->dropToken($token);
                $tokenAuth->cleanup();
                AjaxTool::returnJsonData(200,'登录成功');
            }else{
                $token = $request->getPost('token');
                if ($tokenAuth->isToken($token)) {
                    $password = $request->getPost('password');
                    $num = Lib_Redis_String::get("litigation_login_check_{$mobile}") ?: 1;
                    $actionData = array(
                        'source_type' => '1',
                        'action_type' => '4',
                        'action_time' => time(),
                        'action_uid' => '0',
                        'action_uname' => '',
                        'mobile' => trim($mobile),
                        'action_group' => 0,
                        'action_des' => '',
                        'action_res' => '1',
                        'action_main' => 'user',
                        'action_event' => 'login',
                    );
                    if (!empty($mobile) && !empty($password)) {
                        $admin = Module_User_Administrator::getInstance()->getAdminByMobilePwd($mobile, $password);
                        if ($num < 15) {
                            if (!empty($admin)) {
                                if ($admin['status'] == 2) {
                                    $actionData['action_des'] = '登录失败，该账号已被禁用,不允许登录';
                                    $actionData['action_res'] = 0;
                                    @Module_Uaction_Hook::onActionData($actionData);
                                    AjaxTool::returnJsonData(403,'登录失败，该账号已被禁用,不允许登录');
                                } else {
                                    if(!$this->checkUserIp($admin)){
                                        AjaxTool::returnJsonData(403,'访问ip不在允许白名单内');
                                    }
                                    $actionData['action_uid'] = $admin['id'];
                                    $actionData['action_uname'] = $admin['name'];
                                    $actionData['action_group'] = $admin['role_id'];
                                    $actionData['action_des'] = '登录成功';
                                    $actionData['action_res'] = 1;
                                    @Module_Uaction_Hook::onActionData($actionData);
                                    //保存用户登录信息
                                    $random_key = UserAuth::setAuth($mobile);
                                    Module_User_Administrator::getInstance()->updateRandomKeyById($admin['id'], $random_key);
                                    $config = Yaf_Registry::get("config")->cookie;
                                    setcookie('random_key', $random_key, null, '/', $config['domain']);
                                    unset($actionData);
                                    $this->_checkpwd($password, $mobile);
                                    //登录成功清除token_access
                                    $tokenAuth->dropToken($token);
                                    $tokenAuth->cleanup();
                                    AjaxTool::returnJsonData(200,'登录成功');
                                }
                            } else {
                                $actionData['action_des'] = '登录失败，用户名或密码错误';
                                $actionData['action_res'] = 0;
                                @Module_Uaction_Hook::onActionData($actionData);
                                Lib_Redis_String::setex("litigation_login_check_{$mobile}", 60 * 15, $num + 1);
                                if ($num > 5) {
                                    AjaxTool::returnJsonData(403,'验证错误次数过多，请核对密码十五分钟后再试。');
                                } else {
                                    AjaxTool::returnJsonData(403,'登录失败，用户名或密码错误，请核对手机号、密码后再试。');
                                }
                            }
                        } else {
                            AjaxTool::returnJsonData(403,'验证错误次数过多，请核对密码十五分钟后再试。');
                        }
                    } else {
                        AjaxTool::returnJsonData(403,'请填写密码');
                    }

                } else {
                    AjaxTool::returnJsonData(401,'token错误，请刷新页面后重新登录。');
                }
            }
        }
    }

    function _checkpwd($newPassword, $mobile)
    {
        $is = false;
        if (strlen(trim($newPassword)) < 8) {
            $is = true;
        }
        if (!preg_match('/(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[A-Za-z0-9]/', trim($newPassword))) {
            $is = true;
        }
        $arr = array(32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 58, 59, 60, 61, 62, 63, 64, 91, 92, 93, 94,);
        $num = strlen($newPassword);
        $t = false;
        for ($i = 0; $i < $num; $i++) {
            if (in_array(ord($newPassword[$i]), $arr)) {
                $t = true;
            }
        }
        if (!$t) {
            $is = true;
        }
        if ($is) {
            Lib_Redis_String::setex("is{$mobile}._problem", 60 * 2, 1);
        }
    }

    /**
     *登录平台获取验证码
     */
    public function sendMobileCodeAction(){
        $request = $this->getRequest();
        $phonenum = $request->getPost('mobile','');
        $vcode = $request->getPost('verification_code');
        if(!isset($_SESSION['VCODE_TYPE_login']) || strtolower($vcode) != strtolower($_SESSION['VCODE_TYPE_login'])) {
            $data['code'] = 400;
            $data['message'] = '请输入正确验证码';
            echo json_encode($data);
            exit;
        }
        $admin = Module_User_Administrator::getInstance()->getByMobile($phonenum);
        if (!$admin) {
            $data['code'] = 400;
            $data['message'] = '请输入系统注册手机号';
            echo json_encode($data);
            exit;
        }
        $code = Lib_Code::getCode(6, true);
        $res = Lib_SMS_Main::sendSMS($phonenum,'logon',[SmartyAdapter::getTplVars('tjzxname'),$code],$case_id=0,['operationUid'=>$admin['id'],'operationName'=>$admin['name'],'mediationOrganId'=>$admin['mediationOrganId']]);
        if($res['code'] != 200){
            echo json_encode($res);
            exit;
        }
        Lib_Code::saveCode($phonenum, $code);
        echo json_encode($res);
        exit;
    }


    public function xieyiAction(){
        SmartyAdapter::$templateName = 'user/xieyi';
    }


    public function noticeAction(){
        Func_Log::write('SMS_Notify', "honnglianStautsNotify",  ',$res=' . json_encode($_REQUEST));
        $return = ["clcode" => "000000"];
        echo json_encode($return);
        exit();

    }
    private function checkUserIp($admin){
        //查看所属部门配置ip
        if(empty($admin['mediationOrganId'])){
            return true;
        }
        //查看角色
        $mediationOrgan = Module_InfoBase_MediationOrgan::getInstance()->getItemById($admin['mediationOrganId']);
        if($mediationOrgan['ipRestrict'] == 0){
            return true;
        }
        $userIP = Lib_Ip::get_ip();
        $whiteIp = explode("|",$mediationOrgan['whiteIp']);
        if(empty($whiteIp)){
            return false;
        }
        if(in_array($userIP, $whiteIp)){
            return true;
        }
        $ipregexp = implode('|', str_replace( array('*','.'), array('\d+','\.') ,$whiteIp));

        $rs = preg_match("/^(".$ipregexp.")$/", $userIP);
        if($rs){
            return true;
        }
        Func_Log::write('login', 'IP NOT ALLOW', 'userIp：' . $userIP .' whiteIp：' . $mediationOrgan['whiteIp']);
        return false;

    }

}
